package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.help.TextWatcherImp;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.AesUtil;
import com.weixin.paleituo.util.KeybordS;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.NetUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoginNewItemView;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Author yichao
 * Time  2017/11/27 16:44
 * Dest  忘记密码
 */

public class ForgetPasswordActivity extends BasePersonActivity {



    @BindView(R.id.tv_comfire_activity_forget_password)
    TextView mTvComfireActivityForgetPassword;
    @BindView(R.id.loginnewItemView_phone_number_activity_forget_password)
    LoginNewItemView mLoginnewItemViewPhoneNumberActivityForgetPassword;
    @BindView(R.id.loginnewItemView_check_code_activity_forget_password)
    LoginNewItemView mLoginnewItemViewCheckCodeActivityForgetPassword;
    @BindView(R.id.loginnewItemView_password_activity_forget_password)
    LoginNewItemView mLoginnewItemViewPasswordActivityForgetPassword;
    private View mForgetPasswordView;
    private EditText mEditTextPhone, mEditTextCheckCode, mEditTextPassword;
    private TextView mTvMessageView;
    private String mPhoneNumberStr;
    private String mCheckCodeStr;
    private String mPasswordStr;
   // private UpLoadPopuWindow mUpLoadPopuWindow;
    private CountDownTimer mCountDownTimer;
    private Disposable mDisposableForgetPassword, mDisposableMsmCode;
    private ImageView mIvIconPhone;
    private ImageView mIvIconPassword;
    private boolean isShowPassword;
    private Dialog mLoadingDialog;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, ForgetPasswordActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initData() {
        super.initData();
        mTvTitle.setVisibility(View.VISIBLE);
        mTvTitle.setText("找回密码");
        mViewline.setVisibility(View.GONE);
        mEditTextPhone = mLoginnewItemViewPhoneNumberActivityForgetPassword.getEtContent();
        mIvIconPhone = mLoginnewItemViewPhoneNumberActivityForgetPassword.getIvIcon();
        mEditTextCheckCode = mLoginnewItemViewCheckCodeActivityForgetPassword.getEtContent();
        mEditTextPassword = mLoginnewItemViewPasswordActivityForgetPassword.getEtContent();
        mIvIconPassword = mLoginnewItemViewPasswordActivityForgetPassword.getIvIcon();
        mTvMessageView = mLoginnewItemViewCheckCodeActivityForgetPassword.getTvGetMessage();
        mTvMessageView.setVisibility(View.VISIBLE);
        mLoginnewItemViewCheckCodeActivityForgetPassword.setDefaultTvMessageStyle("发送验证码");
        mEditTextPhone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        mEditTextPhone.setInputType(InputType.TYPE_CLASS_PHONE);

        mEditTextPassword.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        mEditTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        mEditTextPassword.postInvalidate();
        mEditTextPassword.setSelection(mEditTextPassword.getText().length());
        mEditTextCheckCode.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
        mEditTextCheckCode.setInputType(InputType.TYPE_CLASS_NUMBER);
        mIvIconPhone.setImageResource(R.mipmap.del);

        /*密码*/
        mIvIconPassword.setVisibility(View.VISIBLE);
        mEditTextPassword.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        mEditTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        mEditTextPassword.postInvalidate();
        mEditTextPassword.setSelection(mEditTextPassword.getText().length());

        mIvIconPassword.setImageResource(R.mipmap.eyelash);

        isShowPassword = false;


    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mEditTextPhone.addTextChangedListener(new TextWatcherImp() {


            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mPhoneNumberStr = s.toString();
                showConfirStatue(mPhoneNumberStr, mCheckCodeStr, mPasswordStr);

                if (mCountDownTimer!=null ){
                    mCountDownTimer.cancel();
                }
                showTvMessageCodeStyle("发送验证码");
                if (StringUtils.isEmpty(mPhoneNumberStr)){
                    mIvIconPhone.setVisibility(View.INVISIBLE);
                }else {
                    mIvIconPhone.setVisibility(View.VISIBLE);

                }

            }

        });
        mEditTextCheckCode.addTextChangedListener(new TextWatcherImp() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                mCheckCodeStr = s.toString();
                showConfirStatue(mPhoneNumberStr, mCheckCodeStr, mPasswordStr);

            }

        });
        mEditTextPassword.addTextChangedListener(new TextWatcherImp() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                mPasswordStr = s.toString();
                showConfirStatue(mPhoneNumberStr, mCheckCodeStr, mPasswordStr);
            }


        });

        mIvIconPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditTextPhone.setText("");

            }
        });

        mIvIconPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isShowPassword) {
                    mIvIconPassword.setImageResource(R.mipmap.eye);
                    mEditTextPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mEditTextPassword.postInvalidate();
                    mEditTextPassword.setSelection(mEditTextPassword.getText().length());
                    isShowPassword = true;
                } else {
                    mIvIconPassword.setImageResource(R.mipmap.eyelash);
                    //隐藏密码明文
                    mEditTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mEditTextPassword.postInvalidate();
                    mEditTextPassword.setSelection(mEditTextPassword.getText().length());
                    isShowPassword = false;
                }
            }
        });


        mTvMessageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (!NetUtils.NetwrokIsUseful(ForgetPasswordActivity.this)) {
                    ToastUtils.makeText(R.string.check_internet);

                }

                ApiUtils.getApi().sendMsgCode(Contans.isEncrypt?AesUtil.aesEncrypt(mEditTextPhone.getText().toString().trim()):mEditTextPhone.getText().toString().trim(), Contans.SMSSING_FORGETPASSWORD).subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                             /*   if (mUpLoadPopuWindow == null) {
                                    mUpLoadPopuWindow = new UpLoadPopuWindow(ForgetPasswordActivity.this);
                                }
                                mUpLoadPopuWindow.showAtLocation(v, Gravity.CENTER, 0, 0);

                                mUpLoadPopuWindow.startAnimal();*/
                             if (mLoadingDialog==null){

                                mLoadingDialog = LoadingDialogUtils.createLoadingDialog(ForgetPasswordActivity.this, "");

                             }
                             LoadingDialogUtils.show(mLoadingDialog);


                                mTvMessageView.setEnabled(false);
                                mTvMessageView.setFocusable(false);

                            }
                        }).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<StatusCode<String>>() {


                    @Override
                    public void onSubscribe(Disposable d) {


                        mDisposableMsmCode = d;
                    }

                    @Override
                    public void onNext(StatusCode<String> value) {
                        if (value.isFlag()) {

                            ToastUtils.makeText(getString(R.string.send_msmg_code_success));
                            if (mCountDownTimer == null) {
                                mCountDownTimer = new CountDownTimer(60 * 1000, 1000) {
                                    @Override
                                    public void onTick(long millisUntilFinished) {
                                        mLoginnewItemViewCheckCodeActivityForgetPassword.setCountDownTvMessageStyle(millisUntilFinished / 1000+"");
                                    }
                                    @Override
                                    public void onFinish() {
                                        mTvMessageView.setText("重新获取");
                                        showTvMessageCodeStyle("重新发送");
                                    }
                                };
                            }
                            mCountDownTimer.start();

                        } else {
                            showTvMessageCodeStyle("发送验证码");
                            ToastUtils.makeText(value.getDetailMsg());

                        }

                        LogUtils.i(TAG, value.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                       // mUpLoadPopuWindow.dismiss();
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        showTvMessageCodeStyle("发送验证码");
                        LogUtils.e(TAG, e.toString());
                    }
                    @Override
                    public void onComplete() {
                       // mUpLoadPopuWindow.dismiss();
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                      //  showTvMessageCodeStyle("重新发送");

                    }
                });


            }
        });
        mEditTextPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== 0 && KeybordS.isSoftInputShow(ForgetPasswordActivity.this)) {
                    KeybordS.closeKeybord(mEditTextPassword,ForgetPasswordActivity.this);

                    //关闭键盘
                    return true;//返回true,消费这个事件

                }

                return false;
            }
        });

    }

    private void showTvMessageCodeStyle(String tvContet) {
        if (UIUtils.isPhoneNumber(mPhoneNumberStr)) {
            //是手机号
          mLoginnewItemViewCheckCodeActivityForgetPassword.setCheckPhoneSuceessTvMessageStyle(tvContet);
        } else {
            //不是手机号
         mLoginnewItemViewCheckCodeActivityForgetPassword.setDefaultTvMessageStyle("发送验证码");
        }
    }


    @Override
    protected View getContentView(Context context) {
        mForgetPasswordView = UIUtils.inflate(context, R.layout.activity_forget_password);
        return mForgetPasswordView;
    }


    @OnClick(R.id.tv_comfire_activity_forget_password)
    public void onViewClicked() {
        if (!NetUtils.NetwrokIsUseful(this)) {
            ToastUtils.makeText(R.string.check_internet);
            return;
        }

        if (!UIUtils.isPhoneNumber(mPhoneNumberStr)) {
            ToastUtils.makeText(R.string.check_phone_number);
            return;
        }
        if (!UIUtils.isPasswordFormat(mPasswordStr)) {
            ToastUtils.makeText(R.string.check_password_format);
            return;
        }
        ApiUtils.getApi().forgetPassword(Contans.isEncrypt?AesUtil.aesEncrypt(mPhoneNumberStr):mPhoneNumberStr, Contans.isEncrypt?AesUtil.aesEncrypt(mPasswordStr):mPasswordStr, mCheckCodeStr)
                .subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
           /*     if (mUpLoadPopuWindow == null) {
                    mUpLoadPopuWindow = new UpLoadPopuWindow(ForgetPasswordActivity.this);
                }
                mUpLoadPopuWindow.showAtLocation(mTvComfireActivityForgetPassword, Gravity.CENTER, 0, 0);

                mUpLoadPopuWindow.startAnimal();*/
           if (mLoadingDialog==null){
               mLoadingDialog=LoadingDialogUtils.createLoadingDialog(ForgetPasswordActivity.this,"");
           }
            LoadingDialogUtils.show(mLoadingDialog);

                mTvComfireActivityForgetPassword.setFocusable(false);
                mTvComfireActivityForgetPassword.setEnabled(false);

            }
        }).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<StatusCode<String>>() {


            @Override
            public void onSubscribe(Disposable d) {

                mDisposableForgetPassword = d;
            }

            @Override
            public void onNext(StatusCode<String> value) {
             //   mUpLoadPopuWindow.dismiss();
                LoadingDialogUtils.closeDialog(mLoadingDialog);


                if (value.isFlag()) {
                    ToastUtils.makeText(getString(R.string.reset_password_success));
                    LoginActivity.startActivity(ForgetPasswordActivity.this,false);
                    finish();
                } else {
                    ToastUtils.makeText(value.getDetailMsg());
                }
                LogUtils.e(TAG, "忘记密码::" + value.toString());

            }

            @Override
            public void onError(Throwable e) {
                showConfirStatue(mPhoneNumberStr, mCheckCodeStr, mPasswordStr);
             //   mUpLoadPopuWindow.dismiss();
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                LogUtils.e(TAG, "忘记密码::" + e.toString());
            }

            @Override
            public void onComplete() {
                showConfirStatue(mPhoneNumberStr, mCheckCodeStr, mPasswordStr);


            }
        });

    }
    /**
     * 显示确定的状态
     *
     * @param phoneStr
     * @param checkCodeStr
     * @param passwordStr
     */
    private void showConfirStatue(String phoneStr, String checkCodeStr, String passwordStr) {
        if (!StringUtils.isEmpty(phoneStr) &&UIUtils.isPhoneNumber(phoneStr)&& !StringUtils.isEmpty(checkCodeStr) && !StringUtils.isEmpty(passwordStr)&&UIUtils.isPasswordFormat(passwordStr)) {
            mTvComfireActivityForgetPassword.setFocusable(true);
            mTvComfireActivityForgetPassword.setEnabled(true);
        } else {
            mTvComfireActivityForgetPassword.setFocusable(false);
            mTvComfireActivityForgetPassword.setEnabled(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*if (mUpLoadPopuWindow != null && mUpLoadPopuWindow.isShowing()) {
            mUpLoadPopuWindow.dismiss();
        }*/

     LoadingDialogUtils.closeDialog(mLoadingDialog);

        if (mDisposableForgetPassword != null && !mDisposableForgetPassword.isDisposed()) {
            mDisposableForgetPassword.dispose();
        }
        if (mDisposableMsmCode != null && !mDisposableMsmCode.isDisposed()) {
            mDisposableMsmCode.dispose();
        }

        if (mCountDownTimer!=null){
            mCountDownTimer.cancel();
        }
    }

}
